#/bin/bash

MAIL_DIR=~/mail/inbox/cur

REPORT_FILE_DIR=report_file
FULL_REPORT_DIR=$REPORT_FILE_DIR/full
PART_REPORT_DIR=$REPORT_FILE_DIR/part

OLD_MAIL_FILE=conf/OLDMAIL

# init
mkdir -p "$FULL_REPORT_DIR" "$PART_REPORT_DIR"

function get_mhead()
{
	cat $1 | while read -r l ; do
		[ -z "$l" ] && break
		echo "$l"
	done
}

function get_mbody()
{
	cat $1 | while read -r l ; do
		[ -z "$l" ] && cat
	done
}

function get_mail()
{
	echo start
	local old_file_name=$(<"$OLD_MAIL_FILE")
	local update_flag=
	echo old file name: $old_file_name
	(cd "$MAIL_DIR" ; ls -t) | while read -r name ; do
		[ "$name" = "$old_file_name" ] && break
		if [ -z "$update_flag" ] ; then
			update_flag="true"
			echo "$name" > "$OLD_MAIL_FILE"
		fi

		if fgrep -x -q 'From: DoNotReplay@fake.cn' "$MAIL_DIR/$name" &&
			mail_head=$(get_mhead "$MAIL_DIR/$name") &&
			subject=$(echo "$mail_head" | grep '^Subject: .*Ensis Monitor Report') ; then
			# TODO need save file
			subject="${subject:9}"		# length of "Subject: "

			time_str="${subject#*(}"
			time_str="${time_str#*PDT: }"
			time_str="${time_str%)*}"
			start_time=$(date +%s -d "${time_str% -*}")
			end_time=$(date +%s -d "${time_str#*- }") 

			if [ "$((end_time - start_time))" -gt $((3600*23)) ] ; then
				out_put_file="$FULL_REPORT_DIR/${start_time}_$subject.html"
			else
				out_put_file="$PART_REPORT_DIR/${start_time}_$subject.html"
			fi

			if [ -f "$out_put_file" ] ; then
				echo "$out_put_file already exist!!"
			else
				echo "put $MAIL_DIR/$name's mail boyd to $out_put_file"
				get_mbody "$MAIL_DIR/$name" > "$out_put_file"
			fi
		fi

	done

	echo end
}

get_mail

# note TODO
# save file format: times() + orion filename
